<template>
  <el-aside width="200px">
    <el-scrollbar>
      <el-menu @select="handleSelect" :default-active="active" :default-openeds="openeds">
        <!-- 遍历一级菜单 -->
        <el-sub-menu v-for="menu in menus" :key="menu.id" :index="menu.path" v-show="menu?.show">
          <template #title>
            {{ menu.name }}
          </template>

          <!-- 遍历二级菜单 -->
          <el-menu-item
            v-for="child in menu.children"
            :key="child.id"
            :index="child.path"
            v-show="child?.show"
          >
            {{ child.name }}
          </el-menu-item>
        </el-sub-menu>
      </el-menu>
    </el-scrollbar>
  </el-aside>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import router from '@/router'
import { menu_permission } from '@/api/auth'

const menus = menu_permission.value
const active = ref('') // 默认激活菜单的路径
const openeds = ref<string[]>([]) // 存储默认展开的菜单

// 判断是否为可迭代对象
function isIterable(obj: any): boolean {
  return obj != null && typeof obj[Symbol.iterator] === 'function'
}

onMounted(() => {
  // 检查菜单数据是否可迭代
  if (!isIterable(menus)) {
    // 如果菜单不可迭代，跳转到登录页面
    router.push('/login')
    return
  }

  // 找到第一个可见的子菜单并设置为默认激活菜单
  for (const menu of menus) {
    if (menu.show) {
      openeds.value.push(menu.path)
      for (const child of menu.children) {
        if (child.show) {
          active.value = child.path // 设置为第一个可见子菜单的路径
          router.push(active.value)
          return // 找到后退出
        }
      }
    }
  }
})

const handleSelect = (path: string) => {
  router.push(path)
}
</script>
